import React from 'react'
import {Card,Row,Col,Button,Icon,Form, Input,message,Spin } from 'antd';
import {Link} from 'react-router-dom'
import PureRenderMixin from 'react-addons-pure-render-mixin'

import LeftMenu from 'component/leftmenu/index.jsx';
import HeadImgContent from 'component/headimgcontent/index.jsx';
import LeftMenuItem from 'component/leftmenuitem/index.jsx';


import MMUtile from 'util/mm.jsx'
import User from 'service/user-service.jsx'
import Safty from 'service/safty-service.jsx'
import Verify from 'component/verify/index.jsx';
const _mm = new MMUtile();
const _user = new User();
const _safty = new Safty();


const FormItem = Form.Item;


let residences = [];


let userInfo = _mm.getStorage('userInfo')?JSON.parse(_mm.getStorage('userInfo')):{};
class UpdatePhoneForm extends React.Component{
	constructor(props){
		super(props);
		this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
		this.state = {

			Phone:'',
			isFirstPhone:true,
			items:[{'name':'修改密码','actived':false,'link':'/updatepsw','icon':'edit'},
			{'name':'密保设置','actived':false,'link':'/security','icon':'key'},
			{'name':'绑定手机','actived':true,'link':'','icon':'mobile'},
			{'name':'登录邮箱','actived':false,'link':'/updateemail','icon':'mail'},
			{'name':'登录记录','actived':false,'link':'/recordsafty','icon':'profile'}],
			loading:true
		}

	}
	componentWillMount(){
		//获取手机号
		_safty.getUserPhone().then((res)=>{
			if(res){
				this.setState({
					Phone:res,
					isFirstPhone:false
				})
			}
			this.setState({
				loading:false
			})
		},(errMsg)=>{

			this.setState({
				loading:false
			})
			_mm.errorTips(errMsg)
		})
	}
	componentWillUpdate(){
		userInfo = _mm.getStorage('userInfo')?JSON.parse(_mm.getStorage('userInfo')):{};
	}
	checkPhone(rule, value, callback){
    const form = this.props.form;
    const phone = form.getFieldValue('Phone')
    if(!(/^1[34578]\d{9}$/.test(phone))){ 
        callback("手机号码有误，请重填");  
    }  else {
    	
      callback();
    }
  }
	handleSubmit(e){
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
    	if (err) {
        return;
      }
      _user.checkPhone({
				phone:values.Phone
			}).then((res)=>{
				_safty.updatePhone({
					phone:values.Phone
				}).then((res)=>{
					let sessionPhone = values.Phone.substr(0, 3)+"****"+values.Phone.substr(-4, 4);
					userInfo.phone = sessionPhone;
					_mm.setStorage('userInfo',userInfo);
					message.success('用户手机号保存成功');
					this.props.history.push('/');
				},(errMsg)=>{
					_mm.errorTips(errMsg);
				})
			},(errMsg)=>{
				_mm.errorTips(errMsg);
			})
			
      
    });
  }

	getIsCodeRight(callback){
		this.setState({
			isFirstPhone:callback.isCodeRight,
			Phone:''
		})
	}
	render(){
		const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
      },
    };
		return(
			
			<div>
				<Row gutter={24}>
					<Col span={7}>
		        <Card bordered={true} className="itemminheight"><LeftMenuItem items={this.state.items}></LeftMenuItem></Card>
		      </Col>
		      <Col span={17}>
		      	<Spin spinning={this.state.loading}   size="large">
						{
							this.state.isFirstPhone
							?
							<Form onSubmit={this.handleSubmit.bind(this)}>
				        <Card title="绑定手机号码" bordered={false}>
				        	
				        	<Row>
				        		<Col span={12}>
											<FormItem
												{...formItemLayout}
							          label="用户手机">
							          {getFieldDecorator('Phone', {
					            		rules: [{ required: true, message: '请输入您的注册手机号!' }, { validator: this.checkPhone.bind(this) }],
							            initialValue:this.state.Phone,
							          })(
							          <Input placeholder="请输入手机号码" />)}
							        </FormItem>
				        		</Col>
				        	</Row>
				        	<FormItem>
					          <Button
					            type="primary"
					            htmlType="submit"
					          >
					            提交
					          </Button>
					        </FormItem>
				        </Card>
							</Form>
							:
							<Card title="修改手机号码" bordered={false}>
			        	<Row>
			        		<Col span={12}>
										<Verify phone={userInfo.phone} email={userInfo.email} getIsCodeRight={this.getIsCodeRight.bind(this)}></Verify>
			        		</Col>
			        	</Row>
							</Card>
						}
						
						</Spin>
		      </Col>
				</Row>
			</div>
		)
	}
}
const UpdatePhone = Form.create()(UpdatePhoneForm);
export default UpdatePhone;